package com.gateway.filter;

import com.common.dubbo.sbxBase.UserRPC;
import com.common.entity.sbxBase.User;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;


@Configuration
public class MyGlobalFilters implements GlobalFilter, Ordered {
    @DubboReference
    private UserRPC userRPC;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

//        RequestPath path = exchange.getRequest().getPath();
//        if (judgePath(path.toString()).equalsIgnoreCase("login")) {
//            System.out.println("登录");
//        }

        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();

        HttpCookie authentication = cookies.getFirst("authentication");
        if (!Objects.isNull(authentication)) {
            String value = authentication.getValue();
            System.out.println(value);
            User user = userRPC.getUserInfoBySession(value);


            ServerHttpRequest newRequest = exchange.getRequest().mutate().headers(httpHeaders -> {
                httpHeaders.add("userId", user.getId());
                httpHeaders.add("roleId",user.getRoleId());
                httpHeaders.add("username",user.getUserName());
                httpHeaders.add("nickname",user.getNickName());
            }).build();
            return chain.filter(exchange.mutate().request(newRequest).build());
        }

      return chain.filter(exchange);


    }

    public String judgePath(String path){
        String[] split = path.split("/");
        return split[split.length-1];
    }



    @Override
    public int getOrder() {
        return -1;
    }
}
